package com.wey.springboot.util;

import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class StringUtil {
  static Pattern linePattern = Pattern.compile("_(\\w)");
  static Pattern humpPattern = Pattern.compile("[A-Z]");
  static String wordString = "abcdefghijklmnopqrstuvwxyz";
  static String numberString = "0123456789";
  static String charString = "";

  static {
    String s = wordString.toUpperCase();
    wordString = wordString + s;
    charString = wordString + numberString;
  }

  // 获取随机字母字符串
  public static String getRandomWord(int length) {
    StringBuilder stringBuilder = new StringBuilder();
    int len = wordString.length();
    for (int i = 0; i < length; i++) {
      stringBuilder.append(wordString.charAt((int) (Math.random() * len)));
    }
    return stringBuilder.toString();
  }

  // 获取随机数字字符串
  public static String getRandomNumber(int length) {
    int len = numberString.length();
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < length; i++) {
      stringBuilder.append(numberString.charAt((int) (Math.random() * len)));
    }
    return stringBuilder.toString();
  }

  // 获取随机字符串
  public static String getRandomString(int length) {
    int len = charString.length();
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < length; i++) {
      stringBuilder.append(charString.charAt((int) (Math.random() * len)));
    }
    return stringBuilder.toString();
  }

  // 下划线转驼峰
  public static String toHump(String str) {
    str = str.toLowerCase();
    Matcher matcher = linePattern.matcher(str);
    StringBuilder sb = new StringBuilder();
    while (matcher.find()) {
      matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
    }
    matcher.appendTail(sb);
    return sb.toString();
  }

  // 驼峰转下划线
  public static String toUnderLine(String str) {
    Matcher matcher = humpPattern.matcher(str);
    StringBuilder sb = new StringBuilder();
    while (matcher.find()) {
      matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
    }
    matcher.appendTail(sb);
    return sb.toString();
  }
}
